// node 40_this指向.js

//箭头函数中的this
//（1）箭头函数中的this继承于其上层函数作用域
//（2）其this在箭头函数被定义那一刻才确定

// 实例    this指向实例
// 对象    this指向被调用对象
// 全局    windows
// bind，apply 和 call
// 箭头函数

//题1
name = 'windows'
var obj1 = {
    name:'obj1_name',
    fn1:function () {
        console.log(this.name)
    },
    fn2:()=>{console.log(this.name)},
    fn3:function () {
        return function () {
            console.log(this.name)
        }
    },
    fn4:function () {
        return ()=>{console.log(this.name)}
    }
}
var obj2 = {
    name:'obj2_name',
}

console.log('-----fn1');
//
obj1.fn1();//--->obj1_name
//call将fn1的this指向改变为了obj2
obj1.fn1.call(obj2);//--->obj2_name

console.log('-----fn2');
// 
obj1.fn2();//--->obj1_name
//call改变了调用fn2的this,但是箭头函数自生没有this，其内部this是其上一次的this,另外箭头函数的this在函数生成时才指定
obj1.fn2.call(obj2);//--->obj1_name

console.log('-----fn3');
//var fn = obj1.fn3()   fn()     
obj1.fn3()();//--->windos
//相当于obj2在call的帮助下调用了obj1中的fn3方法返回的函数
obj1.fn3().call(obj2);//--->obj2_name
//var fn = obj1.fn3().call(obj2)   fn()
obj1.fn3.call(obj2)();//--->windos

console.log('-----fn4');
//var fn = obj1.fn4()  fn()
//fn()是一个箭头函数,其上层函数属于obj1中的函数,所以其内部this表示obj1
obj1.fn4()();//--->obj1_name
//相当于obj2在call的帮助下调用了obj1中的fn4方法返回的函数
obj1.fn4().call(obj2);//--->obj1_name
//var fn = obj1.fn4.call(obj2)  fn()   
//fn()是一个箭头函数，其上层函数被obj2所调用，所以其内部this表示obj2
obj1.fn4.call(obj2)();//--->obj2_name


//题2
obj = {
    func() {
        const arrowFunc = () => {
        console.log(this._name)
        }

        return arrowFunc
    },

    _name: "obj",
}

//var fn = obj.func() fn()
obj.func()()//obj

func = obj.func
//var fn = func() fn()
func()()//undefined

//var fn = {_name: "newObj" }.func()  fn()
obj.func.bind({ _name: "newObj" })()()//newObj

//var fn = func() fn()
obj.func.bind()()()//undefined

//var fn = { _name: "bindObj" }.func() fn()
obj.func.bind({ _name: "bindObj" }).apply({ _name: "applyObj" })()//bindObj

